package ltd.itlover.yqblog.blog;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;


import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnFooterRefreshListener;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import ltd.itlover.yqblog.R;

import ltd.itlover.yqblog.entity.BlogListBrief;
import ltd.itlover.yqblog.dto.Result;
import ltd.itlover.yqblog.network.BlogApiService;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
@SuppressWarnings("all")
@AndroidEntryPoint
public class BlogFragment extends Fragment {

    @Inject
    BlogApiService blogApiService;

    private BlogAdapter blogAdapter;

    private List<BlogListBrief> blogListBriefs = new ArrayList<>();


    private View view;
    private UltimateRefreshView mUltimateRefreshView;
    private int page;
    private int currentPage = 2;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        //从网路上加载数据到数据库

        view = inflater.inflate(R.layout.fragment_blog, container, false);

        //初始化RecycleView
        RecyclerView recyclerView = view.findViewById(R.id.blog_list_rccv);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        blogAdapter = new BlogAdapter(blogListBriefs);
        recyclerView.setAdapter(blogAdapter);


        requestData(1);


        //配置上下拉刷新组件
        mUltimateRefreshView = (UltimateRefreshView) view.findViewById(R.id.refreshView);
        mUltimateRefreshView.setBaseHeaderAdapter(new BlogRefreshHeaderAdapter(getContext()));
        mUltimateRefreshView.setBaseFooterAdapter(new BlogFooterRefreshAdapter(getContext()));

        //下拉更新数据操作
        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {
                requestData(1);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mUltimateRefreshView.onHeaderRefreshComplete();
                    }
                }, 2000 );
            }

        });

        //上拉追加底部数据操作
        mUltimateRefreshView.setOnFooterRefreshListener(new OnFooterRefreshListener(){
            @Override
            public void onFooterRefresh(UltimateRefreshView view) {
                requestData(currentPage);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mUltimateRefreshView.onFooterRefreshComplete();
                    }
                }, 1200);
            }
        });
        return view;
    }

    private void loadDataIntoPage(){
        blogListBriefs.clear();
        blogListBriefs.addAll(DataSupport.findAll(BlogListBrief.class)) ;
        blogAdapter.notifyDataSetChanged();
        Log.i("测试", blogListBriefs.size()+"");
    }
    private void requestData(int cPage){
        blogApiService
                .getBlogBriefList(cPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Result<List<BlogListBrief>>>() {
                    @Override
                    public void accept(Result<List<BlogListBrief>> listResult) throws Exception {
                        if(cPage == 1){
                            DataSupport.deleteAll(BlogListBrief.class);
                            makeInfo("已是最新的数据");
                            currentPage = 2;
                        }
                        else{
                            if (listResult.getData().size() == 0){
                                makeInfo("亲亲, 人家是有底线的哟");
                            }
                            else{
                                currentPage ++;
                            }

                        }
                        DataSupport.saveAll(listResult.getData());
                        loadDataIntoPage();

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        makeInfo("网络请求错误");
                        loadDataIntoPage();
                    }

                });
    }



    public void makeInfo(String info){
        Toast.makeText(this.getActivity(), info, Toast.LENGTH_SHORT).show();
    }
}